/*
 * Copyright (C) 2009-2011 Geometer Plus <contact@geometerplus.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */

package com.esp.soccertutor.android.fbreader;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;


import com.esp.soccertutor.R;
import com.esp.soccertutor.android.util.UIUtil;
import com.esp.soccertutor.fbreader.fbreader.FBReaderApp;
import com.esp.soccertutor.fbreader.library.Book;
import com.esp.soccertutor.fbreader.library.Bookmark;
import com.esp.soccertutor.uc.Table_Content_BottomMenu;
import com.esp.soccertutor.util.Const;
import com.esp.soccertutor.zlibrary.core.application.ZLApplication;
import com.esp.soccertutor.zlibrary.core.options.ZLStringOption;
import com.esp.soccertutor.zlibrary.core.resources.ZLResource;
import com.esp.soccertutor.zlibrary.core.util.ZLMiscUtil;

public class BookmarksActivity extends Activity {
	private static final int OPEN_ITEM_ID = 0;
	private static final int EDIT_ITEM_ID = 1;
	private static final int DELETE_ITEM_ID = 2;
	private Table_Content_BottomMenu tocmenu;
	public  List<Bookmark> AllBooksBookmarks;
	public  final List<Bookmark> myThisBookBookmarks = new LinkedList<Bookmark>();
	private final List<Bookmark> mySearchResults = new LinkedList<Bookmark>();

	private TextView txtBookMarktitle;
	
	private ListView myThisBookView;
	
	private Button btnread;
	
	private final ZLResource myResource = ZLResource.resource("bookmarksView");
	private final ZLStringOption myBookmarkSearchPatternOption =
		new ZLStringOption("BookmarkSearch", "Pattern", "");

	public BookmarksActivity(){
		
	}
	
	@Override
	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);

		Thread.setDefaultUncaughtExceptionHandler(new com.esp.soccertutor.zlibrary.ui.android.library.UncaughtExceptionHandler(this));

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
		
		setContentView(R.layout.bookmarks);
		
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		
		txtBookMarktitle = (TextView)findViewById(R.id.txtBookMarktitle);
		txtBookMarktitle.setTypeface(Const.tf);
		
		myThisBookView = (ListView) findViewById(R.id.this_book);
		
		btnread=(Button)findViewById(R.id.btnRead);
		btnread.setOnClickListener(new OnClickListener() {			
			
			public void onClick(View v) {
				startActivity(new Intent(BookmarksActivity.this, FBReader.class));
			}
		});
		
		tocmenu = new Table_Content_BottomMenu(this,getLayoutInflater());
		
		final SearchManager manager = (SearchManager)getSystemService(SEARCH_SERVICE);
		manager.setOnCancelListener(null);

		AllBooksBookmarks = Bookmark.bookmarks();
		Collections.sort(AllBooksBookmarks, new Bookmark.ByTimeComparator());
		final FBReaderApp fbreader = (FBReaderApp)ZLApplication.Instance();

		
		if (fbreader.Model != null) {
			final long bookId = fbreader.Model.Book.getId();
			for (Bookmark bookmark : AllBooksBookmarks) {
				if (bookmark.getBookId() == bookId) {
					System.out.println("BOOOOOOOOOOOOOOOOOOOOOOOOK");
					myThisBookBookmarks.add(bookmark);
				}
			}
		new BookmarksAdapter(myThisBookView, myThisBookBookmarks, true);
		} else {
			findViewById(R.id.this_book).setVisibility(View.GONE);
		}
	}

	@Override
	protected void onNewIntent(Intent intent) {
		if (!Intent.ACTION_SEARCH.equals(intent.getAction())) {
			return;
		}
	   	String pattern = intent.getStringExtra(SearchManager.QUERY);
		myBookmarkSearchPatternOption.setValue(pattern);

		final LinkedList<Bookmark> bookmarks = new LinkedList<Bookmark>();
		pattern = pattern.toLowerCase();
		for (Bookmark b : AllBooksBookmarks) {
			if (ZLMiscUtil.matchesIgnoreCase(b.getText(), pattern)) {
				bookmarks.add(b);
			}
		}
		if (!bookmarks.isEmpty()) {
			//showSearchResultsTab(bookmarks);
		} else {
			UIUtil.showErrorMessage(this, "bookmarkNotFound");
		}
	}

	@Override
	public void onPause() {
		
		for (Bookmark bookmark : AllBooksBookmarks) {
			bookmark.save();
		}
		super.onPause();
	}

	/*@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		final MenuItem item = menu.add(
			0, 1, Menu.NONE,
			myResource.getResource("menu").getResource("search").getValue()
		);
		item.setOnMenuItemClickListener(this);
		item.setIcon(R.drawable.ic_menu_search);
		return true;
	}*/

	@Override
	public boolean onSearchRequested() {
		startSearch(myBookmarkSearchPatternOption.getValue(), true, null, false);
		return true;
	}

	/*void showSearchResultsTab(LinkedList<Bookmark> results) {
		if (mySearchResultsView == null) {
			mySearchResultsView = createTab("searchResults", R.id.search_results);
			new BookmarksAdapter(mySearchResultsView, mySearchResults, false);
		} else {
			mySearchResults.clear();
		}
		mySearchResults.addAll(results);
		mySearchResultsView.invalidateViews();
		mySearchResultsView.requestLayout();
		getTabHost().setCurrentTabByTag("searchResults");
	}*/

	public boolean onMenuItemClick(MenuItem item) {
		switch (item.getItemId()) {
			case 1:
				return onSearchRequested();
			default:
				return true;
		}
	}

	private void invalidateAllViews() {
		
		myThisBookView.invalidateViews();
		myThisBookView.requestLayout();
		/*myAllBooksView.invalidateViews();
		myAllBooksView.requestLayout();*/
		/*if (mySearchResultsView != null) {
			mySearchResultsView.invalidateViews();
			mySearchResultsView.requestLayout();
		}*/
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		final int position = ((AdapterView.AdapterContextMenuInfo)item.getMenuInfo()).position;
//		final ListView view = (ListView)getTabHost().getCurrentView();
		final ListView view = (ListView)findViewById(R.id.this_book);
		
		final Bookmark bookmark = ((BookmarksAdapter)view.getAdapter()).getItem(position);
		switch (item.getItemId()) {
			case OPEN_ITEM_ID:
				gotoBookmark(bookmark);
				return true;
			case EDIT_ITEM_ID:
        		final Intent intent = new Intent(this, BookmarkEditActivity.class);
        		startActivityForResult(intent, 1);
				// TODO: implement
				return true;
			case DELETE_ITEM_ID:
				bookmark.delete();
				myThisBookBookmarks.remove(bookmark);
				AllBooksBookmarks.remove(bookmark);
				mySearchResults.remove(bookmark);
				invalidateAllViews();
				return true;
		}
		return super.onContextItemSelected(item);
	}

	public void addBookmark() {
		
		final FBReaderApp fbreader = (FBReaderApp)ZLApplication.Instance();
		final Bookmark bookmark = fbreader.addBookmark(20,true);
		if (bookmark != null) {
			myThisBookBookmarks.add(0, bookmark);
			AllBooksBookmarks.add(0, bookmark);
			invalidateAllViews();
		}
	}

	private void gotoBookmark(Bookmark bookmark) {
		
		bookmark.onOpen();
		System.out.println("############################[===2====]");
		final FBReaderApp fbreader = (FBReaderApp)ZLApplication.Instance();
		final long bookId = bookmark.getBookId();
		System.out.println("############################[===3====]+BookID ::"+bookId);
		
		if ((fbreader.Model == null) || (fbreader.Model.Book.getId() != bookId)) {
			
			final Book book = Book.getById(bookId);
			if (book != null) {
				finish();
				System.out.println("############################[===4.1====]");
				fbreader.openBook(book, bookmark);
			} else {
				System.out.println("############################[===4.2====]");
				UIUtil.showErrorMessage(this, "cannotOpenBook");
			}
			
		} else {
			
			finish();
			TOCActivity.flag = true;
			System.out.println("############################[===4.3====]");
			fbreader.gotoBookmark(bookmark);
		}
	}

	private final class BookmarksAdapter extends BaseAdapter implements AdapterView.OnItemClickListener, View.OnCreateContextMenuListener {
		private final List<Bookmark> myBookmarks;
		private final boolean myCurrentBook;

		BookmarksAdapter(ListView listView, List<Bookmark> bookmarks, boolean currentBook) {
			myBookmarks = bookmarks;
			myCurrentBook = currentBook;
			listView.setAdapter(this);
			listView.setOnItemClickListener(this);
			listView.setOnCreateContextMenuListener(this);
		}

		public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
			final int position = ((AdapterView.AdapterContextMenuInfo)menuInfo).position;
			if (getItem(position) != null) {
				menu.setHeaderTitle(getItem(position).getText());
				final ZLResource resource = ZLResource.resource("bookmarksView");
				menu.add(0, OPEN_ITEM_ID, 0, resource.getResource("open").getValue());
				//menu.add(0, EDIT_ITEM_ID, 0, resource.getResource("edit").getValue());
				menu.add(0, DELETE_ITEM_ID, 0, resource.getResource("delete").getValue());
			}
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			
			final View view = (convertView != null) ? convertView :
				LayoutInflater.from(parent.getContext()).inflate(R.layout.bookmark_item, parent, false);
			final ImageView imageView = (ImageView)view.findViewById(R.id.bookmark_item_icon);
			final TextView textView = (TextView)view.findViewById(R.id.bookmark_item_text);
			final TextView bookTitleView = (TextView)view.findViewById(R.id.bookmark_item_booktitle);

			final Bookmark bookmark = getItem(position);
			if (bookmark == null) {
				imageView.setVisibility(View.VISIBLE);
				imageView.setImageResource(R.drawable.ic_list_plus);
				textView.setText(ZLResource.resource("bookmarksView").getResource("new").getValue());
				bookTitleView.setVisibility(View.GONE);
			} else {
				imageView.setVisibility(View.GONE);
				textView.setText(bookmark.getText());
				if (myCurrentBook) {
					bookTitleView.setVisibility(View.GONE);
				} else {
					bookTitleView.setVisibility(View.VISIBLE);
					bookTitleView.setText(bookmark.getBookTitle());
				}
			}
			return view;
		}

		@Override
		public final boolean areAllItemsEnabled() {
			return true;
		}

		@Override
		public final boolean isEnabled(int position) {
			return true;
		}

		public final long getItemId(int position) {
			return position;
		}
	
		public final Bookmark getItem(int position) {
			if (myCurrentBook) {
				--position;
			}
			return (position >= 0) ? myBookmarks.get(position) : null;
		}

		public final int getCount() {
			return myCurrentBook ? myBookmarks.size() + 1 : myBookmarks.size();
		}

		public final void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			
			final Bookmark bookmark = getItem(position);
			if (bookmark != null) {
				System.out.println("############################[===1====]position :["+position+"]");
				gotoBookmark(bookmark);
			} else {
				System.out.println("############################ ADD BOOK MARK" + position);
				addBookmark();
			}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) { 
	    if (keyCode == KeyEvent.KEYCODE_MENU) {
	    	System.out.println("PRESSED MENU BUTTON");
	    	doMenu();
	    	return true; //always eat it!	    	
	    }
	    else if(keyCode == KeyEvent.KEYCODE_BACK)
	    {
	    	if (tocmenu.isShowing()) {
	    		tocmenu.hide();
				return true;
	    	}
	    }
		return super.onKeyDown(keyCode, event); 
	} 
	private void doMenu() {
		if (tocmenu.isShowing()) {
			tocmenu.hide();
		} else {
			//Note it doesn't matter what widget you send the menu as long as it gets view.
			tocmenu.show(findViewById(R.id.this_book));
		}
	}
}
